import { getOrgProducts, getValidSelected } from '@/dataTransfer/productCart';
import {
  batchDeleteProductsServer,
  productCarDeleteProductId,
  productCarUpdateProductNum,
} from '@/services/productCar';
import { getProductCarListService } from '@/services/takeOut';
import Taro from '@tarojs/taro';

function delay(timeout) {
  return new Promise((resolve) => {
    setTimeout(resolve, timeout);
  });
}

let status = {
  from: undefined,
  when: 0,
};

export default {
  namespace: 'productCar',
  state: {
    cartList: undefined, // 购物车所有店铺列表
    cartProductList: undefined, // 购物车所有商品列表
    invalidList: undefined, // 购物车 失效商品
    orgOverDistributionList: undefined, // 购物车超出配送范围外卖店铺列表

    cartSelected: [], // 购物车已选择商品id,确保重新进入购物车，商品处于选择状态
    cartSelectedChange: {}, //购物车商品勾选状态变更的商品id集合{unChooseIds:[],chooseIds:[]}
    isResetCartSelectedChange: false,
    cartShopSelected: [], // 点击立即购买需要暂存的商品id
    cartShopProductReleaseIds: [], // 立即购买商品id, 用于查询商品配送方式
    buyNow: {}, // 立即购买缓存 需要及时清理
    defaultAddress: {}, // 购物默认地址
    giftCardSelected: [], // 已选礼品卡{}
    eInvoiceSelected: {}, // 已选电子发票对象
    selectedAddress: {},
    locationAddress: null,
    selectedAddressTakeOut: {},
  },

  effects: {
    // 批量删除购物车商品列表
    *batchDeleteProducts({ payload }, { call }) {
      const res = yield call(batchDeleteProductsServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }
      return res.content;
    },

    *getCartList({ payload, from }, { select, call, put }) {
      const isResetCartSelectedChange = yield select(
        ({ productCar }) => productCar.isResetCartSelectedChange,
      );
      if (isResetCartSelectedChange) {
        yield put({
          type: 'setIsResetCartSelectedChange',
          payload: false,
        });
        return;
      }
      let now = Date.now();
      // 记录本次请求时间戳
      status = { from, when: now };

      // 等待 200 毫秒
      yield call(delay, 200);

      // 存在2个购物车页面, standardCartPage为后台一直存活
      // 当 cartSin 请求的时候, 同时会触发 standardCartPage的请求, 需要把 standardCartPage的请求丢弃
      if (
        (from === 'cartSin' && status.from === 'standardCartPage') ||
        (status.from === 'cartSin' && from === 'standardCartPage')
      ) {
        if (Math.abs(now - status.when) < 200 && from === 'standardCartPage') {
          console.warn('ignore standardCartPage request', {
            current: { from, when: now },
            last: status,
          });
          return Promise.resolve();
        }
      }

      const res = yield call(getProductCarListService, payload);
      const {
        code,
        content: { productCarOrgList = [], orgOverDistributionList = [], invalidList = [] } = {},
      } = res;

      if (code !== '1') {
        return Promise.reject();
      }

      yield put({
        type: 'setCartList',
        payload: {
          cartList: productCarOrgList,
          orgOverDistributionList,
          invalidList,
          cartProductList: getOrgProducts(productCarOrgList),
        },
      });
      const cartSelectedChange = yield select(({ productCar }) => productCar.cartSelectedChange);
      if (cartSelectedChange && Object.keys(cartSelectedChange)?.length > 0) {
        yield put({
          type: 'resetCartSelectedChange',
          payload: {},
        });
      }
      const cartSelected = yield select(({ productCar }) => productCar.cartSelected);
      yield put({
        type: 'setCartSelect',
        payload: cartSelected.slice(),
      });
    },
    *updateProductNum({ payload }, { call }) {
      const res = yield call(productCarUpdateProductNum, payload);
      const { code, content, message } = res;
      if (code === '1') {
        if (content.inventoryQuantity?.length > 0) {
          Taro.showToast({
            title: '该商品当前库存为' + content.inventoryQuantity + '件',
            icon: 'none',
            mask: false,
            duration: 2500,
          });
        }
        return Promise.resolve();
      } else {
        return Promise.reject(message);
      }
    },
    *deleteDeleteProduct({ payload }, { call, put }) {
      const res = yield call(productCarDeleteProductId, payload);
      const { code, message } = res;
      if (code === '1') {
        // 重新获取购物车数量
        yield put({ type: 'productList/getCarNum', payload: {} });

        return Promise.resolve();
      } else {
        return Promise.reject(message);
      }
    },
  },
  reducers: {
    setCartList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    resetCartList(state) {
      return {
        ...state,
        cartList: undefined,
        invalidList: undefined,
        orgOverDistributionList: undefined,
        cartProductList: undefined,
      };
    },
    setCartSelect(state, { payload }) {
      const { validIds, allProducts, allIds, validProducts } = getValidSelected(
        state.cartList,
        payload,
      );

      console.log('===============debug for setCartSelect==', {
        payload,
        cartList: state.cartList,
        validIds,
        allProducts,
        allIds,
        validProducts,
      });

      return {
        ...state,
        allProducts,
        cartSelected: allIds,
      };
    },
    setCartSelectedChange(state, { payload }) {
      return {
        ...state,
        cartSelectedChange: payload,
      };
    },
    resetCartSelectedChange(state, { payload }) {
      return {
        ...state,
        cartSelectedChange: payload,
        isResetCartSelectedChange: true,
      };
    },
    setIsResetCartSelectedChange(state, { payload }) {
      return {
        ...state,
        isResetCartSelectedChange: payload,
      };
    },
    setCartShopSelected(state, { payload }) {
      const { validIds } = getValidSelected(state.cartList, payload);

      return {
        ...state,
        cartShopSelected: validIds,
      };
    },
    setCartShopProductReleaseIds(state, { payload }) {
      return {
        ...state,
        cartShopProductReleaseIds: payload,
      };
    },
    setCartShopSelectedByTakeOut(state, { payload }) {
      return {
        ...state,
        cartShopSelected: [...payload],
      };
    },
    // 立即购买参数
    setBuyNow(state, { payload }) {
      return {
        ...state,
        buyNow: { ...payload },
      };
    },
    // 购物的默认地址设置
    setDefaultAddress(state, { payload }) {
      let addr = { ...payload };
      if (Object.keys(addr).length > 0) {
        addr.isInit = true;
      }
      return {
        ...state,
        defaultAddress: { ...addr },
      };
    },
    // 选中的礼品卡
    setGiftCardSelect(state, { payload }) {
      return {
        ...state,
        giftCardSelected: [...payload],
      };
    },
    // 购物的默认地址设置
    setInvoiceSelected(state, { payload }) {
      return {
        ...state,
        eInvoiceSelected: { ...payload },
      };
    },
    // 购物车云超地址设置
    setSelectedAddress(state, { payload }) {
      return {
        ...state,
        selectedAddress: { ...payload },
        defaultAddress: { ...payload, isInit: true },
      };
    },
    // 购物车云超定位地址
    setLocationAddress(state, { payload }) {
      return {
        ...state,
        locationAddress: { ...payload },
      };
    },
    // 外卖店铺内地址设置
    setSelectedAddressTakeOut(state, { payload }) {
      return {
        ...state,
        selectedAddressTakeOut: { ...payload },
      };
    },
  },
};
